from django.http import HttpResponse
from models_goods.oo import *
from django.db.models import F
from models_user.models import Url, User


# Create your views here.


class Verify:  # 用于验证
    def __init__(self, session, models):
        self.session = session  # session
        self.models = models  # user模型

    def user_is_verify(self):  # 验证器
        try:
            if self.models.objects.get(id=self.session.get('id')).name == self.session.get('name'):
                return False
        except self.models.DoesNotExist:
            return True

    def url_is_verify(self, path, duty):
        try:
            dutys = list(Url.objects.get(url=path).duty.values_list('duty'))
        except Url.DoesNotExist:
            return False
        else:
            for i in duty:
                if (i[0],) in dutys:
                    return True
            else:
                return False


def permission(func):  # 验证权限
    def add_detail(request):
        try:
            duty = request.session['duty']
        except KeyError:
            return render(request, 'login/login.html', {'mes': '请登录'})
        else:
            verify_obj = Verify(request.session, User)
            if verify_obj.user_is_verify():
                return render(request, 'login/login.html', {'mes': '数据异常，重新登录'})
            elif verify_obj.url_is_verify(request.path, duty):
                return func(request)  # 验证成功
            else:
                return render(request, 'login/login.html', {'mes': '权限不足'})
    return add_detail


# 增加资产明细
@permission
def add_detail(request):
    asset_name_list = AllAssetName().get_info()
    room_name_list = AllRoomsName().get_info_detail()
    user_name_list = AllUserName().get_info()

    context = {
        'asset_name_list': asset_name_list,
        'room_name_list': room_name_list,
        'user_name_list': user_name_list}
    if request.method == 'GET':
        return render(request, 'ribbon/add_detail.html', context)

    elif request.method == 'POST':

        info = request.POST
        for value in info.values():
            if value.strip() == '':
                return HttpResponse('你有丢失一些必传参数')
        try:
            info_obj = StockControl.objects.get(
                                    goods_id=info['asset'],
                                    room_id=info['room'],
                                    user_id=info['user'],
                                    unit=info['unit'],
                                    
                                    )
        except StockControl.DoesNotExist:
                 
            StockControl.objects.create(
                    goods_id=info['asset'],
                    room_id=info['room'],
                    user_id=info['user'],
                    number=int(info['num']),
                    unit=info['unit'],
                )

            context.update({'mes': '添加成功'})
            return render(request, 'ribbon/add_detail.html', context)

        else:
            # info_obj.number+=int(info['num'])
            # info_obj.save() #这个方法修改的是一个值，

            # info_obj.objects.update(number = F('number')+int(info['num']))
            # 这个是不对的，因为update是Queryset的方法，现在的这个info_obj是一个实例对像
            info_obj.number = F('number')+int(info['num'])
            # 这里是将number属性变成了一个方法，而不是一个具体的值

            info_obj.save()

            context.update({'mes': '添加成功'})

            return render(request, 'ribbon/add_detail.html', context)
            

# 以房间进行查询
@permission
def room_asset_query(request):
    room_id = request.GET.get('asset')

    all_room = AllRoomsName().get_info_detail()
    if room_id is None:
        context = {
            'all_room': all_room,
            'room': '资产清单'
        }
        return render(request, 'ribbon/room_asset.html', context)

    if request.method == 'GET':
        rsc = RoomStockControl(room_id)
        room_obj = rsc.room_obj
        info = rsc.room_all_asset()
        if info == '没有该房间':
            return HttpResponse(info)
        else:
            room_id01 = int(room_id)
            context = {
                'info': info,
                'room': '{}号楼{}层{}室，资产清单'.format(room_obj.tower.name, room_obj.floor.name, room_obj.room),
                'all_room': all_room,
                'room_id': room_id01
            }
            return render(request, 'ribbon/room_asset.html', context)


